package com.hlx.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlx.mall.product.domain.PmsCategory;
import com.hlx.mall.product.service.PmsCategoryService;
import com.hlx.mall.product.mapper.PmsCategoryMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author HlX
* @description 针对表【pms_category(商品三级分类)】的数据库操作Service实现
* @createDate 2022-11-18 21:18:00
*/
@Service
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryMapper, PmsCategory>
    implements PmsCategoryService{

    @Resource
    private PmsCategoryMapper pmsCategoryMapper;
    
    /**
     * 返回树的结构的列表
     * @return
     */
    @Override
    public List<PmsCategory> listWithTree() {
        // 1.查出所有分类
        List<PmsCategory> list = baseMapper.selectList(null);
        // 2.组装成父子的树形结构
        return list.stream().filter(pmsCategory -> 
                pmsCategory.getParent_cid() == 0
        ).map((meun) -> {
            meun.setChildren(getChildren(meun, list));
            return meun;
        }).sorted((meun1,meun2)->{
            return (meun1.getSort()==null?0: meun1.getSort()) - (meun2.getSort()==null?0: meun2.getSort());
        }).collect(Collectors.toList());
    }
    
    // 递归查找所有菜单的子菜单
    private List<PmsCategory> getChildren(PmsCategory pmsCategory, List<PmsCategory> all) {
        return all.stream().filter(categoty -> {
            return categoty.getParent_cid() == pmsCategory.getCat_id();
        }).map(catecory->{
            catecory.setChildren(getChildren(catecory, all));
            return catecory;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0: menu1.getSort()) - (menu2.getSort()==null?0: menu2.getSort());
        }).collect(Collectors.toList());   
    }
}




